package com.itmuch.cloud.config;

import feign.RequestInterceptor;
import feign.Retryer;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class FeignConfig {
    /**
     * 配置重试策略
     * OpenFeign 4.x 中需通过@Bean显式定义，不能直接在配置文件中指定类名
     */
    @Bean
    public Retryer feignRetryer() {
        // 自定义重试参数：初始间隔100ms，最大间隔1000ms，最多重试3次
        return new Retryer.Default(100, 1000, 3);
    }

    /**
     * 配置拦截器
     *
     * @return
     */
    @Bean
    public RequestInterceptor customInterceptor() {
        return template -> {
            template.header("X-Custom-Header", "custom-value");
        };
    }

    @Bean
    public feign.codec.Encoder feignEncoder() {
        return new SpringEncoder(new ObjectFactory<HttpMessageConverters>() {
            @Override
            public HttpMessageConverters getObject() {
                List<HttpMessageConverter<?>> converters = new ArrayList<>();
                // 支持UTF-8编码
                StringHttpMessageConverter stringConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
                converters.add(stringConverter);
                converters.add(new MappingJackson2HttpMessageConverter());
                return new HttpMessageConverters(converters);
            }
        });
    }
}
